package middleware;

/**
 * Multicast project Bidois Morgan & Thomas Nunes
 *
 */
import Engine.TypeMessage;
import Test.I_RecvMsgHandler;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Thomas
 */
public class ClientThread extends MulticastManager implements I_ClientMulticastHandler {

    private String name = "NomParDefault";
    private InetAddress address;
    private int port;

    public ClientThread(I_RecvMsgHandler pere) {
        try {
            InetAddress addr = InetAddress.getByName("localhost");
            this.InitializeAsClient(addr, 9090, pere, this);

        } catch (IOException ex) {
            Logger.getLogger(ClientThread.class.getName()).log(Level.SEVERE, "Erreur Client", ex);
        }
    }

    //Fonction qui va donné l'id du client en regardant dans l'annuaire
    private void getMyIdFromDirectory(Directory dir) {
        for (ClientInfos clientInfo : dir.getClientList()) {
            if (clientInfo.getIdClient() == this.idClient) {
                this.address = clientInfo.getAdrClient();
                this.port = clientInfo.getPort();
            }
        }
    }

    @Override
    public void setDirectory(ByteBuffer buff) {
        String strData = new String(buff.array());
        System.out.println("data : " + strData);

        //Method Split
        String[] clients = strData.split("\\|");
        int nbClient = clients.length;
        for (int i = 0; i < nbClient; i++) {
            String[] infoClient = clients[i].split(":");
            String strId = infoClient[0];
            String strAdrWithHost = infoClient[1];
            //Lthe adress is with his hostname, so we can't directly do the Inet.getByAddress...
            String[] adress = strAdrWithHost.split("\\/");
            //we recover the interger of the adress
            String strAdr = adress[1];
            String strPort = infoClient[2];
            String strStatus = infoClient[3];
            try {
                int idLoc = Integer.parseInt(strId);
                int portLoc = Integer.parseInt(strPort);
                ClientInfos clInf = new ClientInfos(idLoc, InetAddress.getByName(strAdr), portLoc);
                directory.addClient(clInf);
            } catch (UnknownHostException ex) {
                Logger.getLogger(ClientThread.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        getMyIdFromDirectory(directory);
        System.out.println(directory.toString());
    }
    
    @Override
    public void createSocketServer(){
        engine.createSocketServer(address, port);
        sayIAmReadyForConnection();
    }
    
    private void sayIAmReadyForConnection(){
        engine.send("".getBytes(), TypeMessage.CLIENT_SERVERSOCKET_READY, idClient);
    }

    @Override
    /**
     * Connection to clients with index superior to it
     */
    public void connectToGroup() {
        ClientInfos client = directory.getClientById(this.idClient);
        int indexClient = directory.getClientList().indexOf(client);
        if (++indexClient < directory.getClientList().size()) {
            while (indexClient < directory.getClientList().size()) {
                ClientInfos ciToConnect = directory.getClient(indexClient);
                engine.connectClientToAnotherClient(ciToConnect.getAdrClient(),ciToConnect.getPort(), ciToConnect.getIdClient());
                indexClient++;
            }
        }
    }
}